<?php

require dirname(__FILE__) . "/../classes/imageClass.php";
require dirname(__FILE__) . "/../classes/connectionFactoryClass.php";
require dirname(__FILE__) . "/../classes/imageDao.php";
require dirname(__FILE__) . "/../classes/validates.php";



$image = new ImageClass();
$c = new ConnectionFactory();
$db = $c->getConnection();
$imageDao = new imageDao($db);
$valid = new validates();



$directory = 'temp/';


$error = array();
$errophoto = array();
$idex = 0;
//$fileFoto = array();
$fileFotoType = array();
$tmpFilePath = array();

$fileFoto = $_FILES['upload']['name'];
$fileFotoType = $_FILES['upload']['type'];
$tmpFile = $_FILES['upload']['tmp_name'];





$dir = $directory;

foreach (scandir($dir) as $item) {
    if ($item == '.' || $item == '..')
        continue;
    unlink($dir . DIRECTORY_SEPARATOR . $item);
}

for ($i = 0; $i < count($fileFoto); $i++) {
    
    $tmpFilePath = $tmpFile[$i];
    $newFilePath = $directory . $fileFoto[$i];

    if ($tmpFilePath != "") {

        if ($valid->validatesPhoto($fileFoto[$i])) {
            if ($tmpFilePath != "") {
                if (!$imageDao->getPhotosByName($fileFoto[$i])) {
                    $novoFile[] = $fileFoto[$i];
                    $newFileType[] = $fileFotoType [$i];

                    if (!move_uploaded_file($tmpFilePath, $newFilePath)) {
                        echo "<script> alert('Foto' . $fileFoto[$i] . 'ja existente'); 
                        window.location='../listAllPhotos.php';</script>";
                    }
                }else{
                    $fotosExistentes[]=$fileFoto[$i];
                }
            } else {
                echo "<script> alert('Selecione um arquivo'); 
          window.location='../upload.php';</script>";
            }
        } else {
            echo "<script> alert('O arquivo . $fileFoto[$i];. não é uma Foto valida'); 
        window.location='listAllPhotos.php';</script>";
        }
    } else {
        echo "<script> alert('Selecione um arquivo'); 
          window.location='upload.php';</script>";
    }
}
?>

